package com.demo.controller.index;

import com.demo.common.model.User;
import com.demo.common.util.WebUtil;
import com.demo.interceptor.WebInterceptor;
import com.demo.service.UserService;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.json.FastJson;
import com.jfinal.kit.HttpKit;

import javax.servlet.http.HttpSession;

public class LoginController extends Controller {

    @Inject
    UserService userService;


    //加载登录页面
    public void index() {
        render("login.html");
    }

    //加载注册页面
    public void reg() {
        render("reg.html");
    }

    //登录系统
    public void login() {
        //String username=getPara("hm");
        //String password=getPara("pwd");
        String json = HttpKit.readData(getRequest());
        User u = FastJson.getJson().parse(json, User.class);
        User user = userService.Login(u.getHm(), u.getPwd());
        if (user != null) {
            setSessionAttr("user", user);
            setAttr("result", 1);
        } else {
            setAttr("result", 2);
        }
        renderJson();
    }

    //登录系统
    public void register() {
        //String username=getPara("hm");
        //String password=getPara("pwd");
        String json = HttpKit.readData(getRequest());
        User u = FastJson.getJson().parse(json, User.class);
        User user = userService.findByHm(u.getHm());
        if(user!=null){
            setAttr("result", 3);
        }else {
            u.setPwd(WebUtil.encrypt(u.getPwd()));
            u.save();
            if (u != null) {
                setSessionAttr("user", u);
                setAttr("result", 1);
            } else {
                setAttr("result", 2);
            }
        }
        renderJson();
    }

    //退出系统
    public void logout() {
        HttpSession session = getSession();
        session.removeAttribute("user");
        redirect("/");
    }
}
